package com.zxw.auth.aspect;

import com.zxw.common.api.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class AuthTokenAspect {

    /// @Around是能够改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                return ResponseEntity
                        .status(200)
                        .body(ApiResult.success(body));
            } else {
                log.error("error:{}", responseEntity.getStatusCode());
                return ResponseEntity
                        .status(200)
                        .body(ApiResult.failed("获取受权码失败"));
            }
        }
        return ResponseEntity
                .status(200)
                .body(ApiResult.failed("获取受权码失败"));
    }
}